package com.data.platform.core.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 客户端工具类
 */
public class ServletUtils {

    /**
     * 获取请求属性
     */
    public static ServletRequestAttributes getRequestAttributes() {
        try {
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            return (ServletRequestAttributes) attributes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        try {
            return Objects.requireNonNull(getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取请求头的值
     *
     * @param header 请求头的名称
     * @return 请求头的值
     */
    public static String getHeader(String header) {
        try {
            return Objects.requireNonNull(getRequest()).getHeader(header);
        } catch (Exception e) {
            return null;
        }
    }
}
